package Product;

import entity.Product;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;

@WebServlet("/favorites")
public class ProductFavorites extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        ProductDao productDao = new ProductDao();

        if ("add".equals(action)) {
            HashMap<String,String> user =  (HashMap<String, String>) request.getSession().getAttribute("user");
            if(user==null){
                request.getRequestDispatcher("login.jsp").forward(request,response);
                return;
            }
            int userId = Integer.parseInt(user.get("userId"));// 从会话中获取用户ID
            String productName = request.getParameter("productName");
            String productDescription = request.getParameter("productDescription");
            double price = Double.parseDouble(request.getParameter("price"));
            String image = request.getParameter("image");
            int stockQuantity = Integer.parseInt(request.getParameter("stockQuantity"));

            Product product = new Product(0, userId, productName, productDescription, price, stockQuantity);
            product.setImage(image);

            productDao.addProduct(product);
        } else if ("delete".equals(action)) {
            // 删除商品
            int productId = Integer.parseInt(request.getParameter("productId"));
            productDao.deleteProduct(productId);
        }else if ("favorites".equals(action)) {
            HashMap<String,String> user =  (HashMap<String, String>) request.getSession().getAttribute("user");
            if(user==null){
                request.getRequestDispatcher("login.jsp").forward(request,response);
                return;
            }
            int userId = Integer.parseInt(user.get("userId"));// 从会话中获取用户ID
            List<HashMap<String, String>> favorites = null;
            try {
                favorites = productDao.getFavoritesByUserId(userId);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            request.setAttribute("favorites", favorites);
            System.out.println(favorites);
            request.getRequestDispatcher("/force").forward(request, response);
        }
    }
}
